<%@ page import="com.itqn.pojo.Product" %>
<%@ page import="com.itqn.service.ProductService" %>
<%@ page import="com.itqn.service.Impl.ProductServiceImpl" %>
<%@ page import="com.itqn.service.CategoryService" %>
<%@ page import="com.itqn.service.Impl.CategoryServiceImpl" %>
<%@ page import="com.itqn.pojo.Category" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加商品</title>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/style/productAdd.css">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/style/common.css">
    <link rel="stylesheet" href="//at.alicdn.com/t/c/font_4586065_3r0pq4hk874.css">


</head>
<body>
<%
    String id = request.getParameter("id");
    //创建业务逻辑层对象
    ProductService productService=new ProductServiceImpl();
    Product product = productService.findById(Integer.valueOf(id));
    request.setAttribute("product",product);
    CategoryService categoryService=new CategoryServiceImpl();
    List<Category> categoryList = categoryService.findAllCategory();
    request.setAttribute("categoryList",categoryList);

%>
<c:import url="../header.jsp"></c:import>
<div class="main">
    <div class="container">
        <div class="contentDIV">
            <div class="contentfirst">
                <input type="hidden" name="id" id="id" value="${product.id}">
                <label>
                    <span>*</span>
                    商品名称:
                </label>
                <input type="text" name="name" id="textName" placeholder="请填写商品名称:" value="${product.name}">
                <span class="Errorinfo"></span>
                <label>
                    <span>*</span>
                    商品分类:
                </label>
                <select name="category" class="select">
                    <c:forEach items="${requestScope.categoryList}" var="categoryList">
                        <option value="${categoryList.id}" ${product.categoryId==categoryList.id?"selected":""}>${categoryList.name}</option>
                    </c:forEach>
                </select>
            </div>
            <div class="contentsecond">
                <label>
                    <span>*</span>
                    商品价格:
                </label>
                <input type="text" id="commodityPrice" value="${product.price}" name="price" placeholder="请填写商品价格:">
                <span class="ErrorinfoPrice"></span>
            </div>
            <div class="contentthirdly">
                <label>
                    <span>*</span>
                    商品图片:
                </label>
                <div class="contentthirdly1">
                    <img src="${product.image}" style="width: 200px; height: 160px">
                    <i class="iconfont icon-wenjianshangchuan uploadlogo" style="font-size: 38px"></i>
                    <input type="file" class="upload file" id="file" name="file">
                    <div class="uploading">上传图片</div>
                </div>
                <p>
                    图片大小不超过2M<br/>
                    仅能上传 PNG JPEG JPG类型图片<br/>
                    建议上传200*200或300*300尺寸的图片<br/>
                </p>
            </div>
            <div class="vegetabledesc">
                <label>
                    <span>*</span>
                    商品描述:
                </label>
                <textarea placeholder="商品描述,最长200字" id="desc" name="desc">${product.description}</textarea>
            </div>

            <div class="subBox">
                <button class="cancel" onclick="history.back()">取消</button>
                <button class="save" onclick="update(${product.id})">修改</button>
            </div>
        </div>
    </div>
</div>
<c:import url="../Leftnavigationbar.jsp"></c:import>
<script src="${pageContext.request.contextPath}/js/jquery.js"></script>
<script src="../../js/a.js"></script>
<script>
    document.querySelector('.contentthirdly1').addEventListener('click', function () {
        document.querySelector('.file').click()
    })
    const textName = document.querySelector('#textName');
    textName.addEventListener('blur', function () {
        if (textName.value == "") {
            document.querySelector('.Errorinfo').innerHTML = '请输入商品名称'
            return
        } else {
            document.querySelector('.Errorinfo').innerHTML = ''
        }
    })
    const Price = document.querySelector('#commodityPrice');
    Price.addEventListener('blur', function () {
        if (Price.value === '' || Price.value < 1) {
            document.querySelector('.ErrorinfoPrice').innerHTML = '商品价格格式有误，请输入大于零且最多保留两位小数的金额'
            return
        } else {
            document.querySelector('.ErrorinfoPrice').innerHTML = ''
        }
    })

    const inputAll = document.querySelectorAll('input')
    for (let i = 0; i < inputAll.length; i++) {
        inputAll[i].addEventListener('focus', function () {
            inputAll[i].style.outline = 'none'
            inputAll[i].style.border = '1px solid rgb(168, 240, 135)'
        })
    }
    for (let i = 0; i < inputAll.length; i++) {
        inputAll[i].addEventListener('blur', function () {
            inputAll[i].style.outline = ''
            inputAll[i].style.border = ''
        })
    }
    document.querySelector('textarea').addEventListener('focus', function () {
        const textarea = document.querySelector('textarea')
        textarea.style.outline = 'none'
    })
    document.querySelector('select').addEventListener('focus', function () {
        const textarea = document.querySelector('select')
        textarea.style.outline = 'none'
    })

    // 业务逻辑
    document.querySelector('.upload').addEventListener('change', e => {
        const fd = new FormData()
        fd.append('file', e.target.files[0])
        $.ajax({
            type: 'post',
            url: '/UploadServlet',
            data: fd,
            processData: false,
            contentType: false,
            cache: false,
            success: res => {
                if (res === '文件上传失败!' || !res) return
                document.querySelector('.contentthirdly1').style.border = 'none'
                document.querySelector('.contentthirdly1 img').classList.add('rounded')
                document.querySelector('.contentthirdly1 img').src = res
            }
        })
    })

    $(function () {
        bind();
        select();
    })
    var str = ""
    function bind(id=<%=request.getParameter("id")%>) {
        $.ajax({
            type: 'get',
            url: '/ProductEchoServlet?id='+id+'',
            dataType:'json',
            success: function (data) {
                var list=eval(data);
                $(list).each(function (i,j){
                    $('#id').val(j.id)
                    $('#textName').val(j.name)
                    $('#commodityPrice').val(j.price)
                    $('.contentthirdly1 img').attr('src',j.image)
                    $('.contentthirdly1').css('border','none')
                    $('#desc').val(j.description);
                })
            }
        })
    }

    function select() {
        $.ajax({
            type: 'post',
            url: '/ProductFindAllServlet',
            data: {},
            success: function (data) {
                var list = eval(data);
                $(list).each(function (i, j) {
                    str += '<option value="' + i + '">' + j.category.name + '</option>'
                })
                $('.select').append('<option>请选择商品分类</option>')
                $('.select').append(str)
            }
        })
    }

    function update(id){
        $.ajax({
            type:"post",
            url:"/ProductUpdateServlet",
            data:{
                id:id,
                name: $('#textName').val(),
                category: $('.select').val(),
                price: $('#commodityPrice').val(),
                file: document.querySelector('.contentthirdly1 img').src,
                desc: $('#desc').val(),
            },
            success:function (data){
                if (data==="ok"){
                    alert("修改成功")
                    window.location.href="/admin/product.jsp";
                }
            }
        })
    }

</script>
</body>
</html>
